package com.mojo.concurrent.concurrent_02_lock;

/**
 * synchronized使用示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/15 14:05
 */
public class Synchronization1 {
    //1.共享资源
    static Integer n = 0;
    static final Object OBJ = new Object();

    public static void main(String[] args) throws InterruptedException {
        //2.多个线程操作共享资源
        Thread t1 = new Thread(Synchronization1::increased);
        Thread t2 = new Thread(Synchronization1::increased);
        t1.start();
        t2.start();

        // join方法，等待代用方法的线程执行完毕
        t1.join();
        t2.join();
        System.out.println(n);
        System.out.println(">>>");
    }

    //3.synchronized方法或代码块
    private static void increased() {
        for (int i = 0; i < 500; i++) {
            synchronized (OBJ) {
                n++;
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public synchronized void syncMethod() {
        int i = 0;
        i++;
    }
}
